{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Hur7D_vLnjK"
      },
      "source": [
        "Copyright 2022 The Google Research Authors.\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "You may obtain a copy of the License at\n",
        "\n",
        "     http://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and limitations under the License."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "B1knjFJwd7QF"
      },
      "outputs": [],
      "source": [
        "# Imports\n",
        "from collections import defaultdict\n",
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "import numpy as np\n",
        "from sklearn.model_selection import train_test_split\n",
        "\n",
        "# Parameters\n",
        "FILENAMES = [\n",
        "    '/content/positive_with_drop.tfrecord', '/content/negative.tfrecord'\n",
        "]\n",
        "SAVED_MODEL_FOLDER = '/content/saved_model'\n",
        "POSITIVE_DATA_LABEL_NAME = 'Standup_chair'\n",
        "CLASS_FEATURE_KEY_ID = 'standup_chair_mapping/label'\n",
        "CLASS_FEATURE_KEY_NAME = 'standup_chair_mapping/label/name'\n",
        "DATA_FEATURE_NAME = 'SENSOR/ACCELEROMETER_WINDOW/floats'\n",
        "DIM_FEATURE_NAME = 'SENSOR/ACCELEROMETER_WINDOW/dimensionality'\n",
        "WINDOW_SIZE_FEATURE_NAME = 'SENSOR/ACCELEROMETER_WINDOW/window_size'\n",
        "PERCENT_TRAIN = 0.6\n",
        "PERCENT_VALIDATION = 0.1\n",
        "PERCENT_TEST = 0.3\n",
        "DATASET_BATCH_SIZE = 32"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "n4SXQJbpeUtz"
      },
      "outputs": [],
      "source": [
        "# Extract dataset from records\n",
        "dataset = tf.data.TFRecordDataset(FILENAMES)\n",
        "\n",
        "# Extracted items from dataset, with dict key representing the label ID of the\n",
        "# data.\n",
        "labeled_dataset = defaultdict(list)\n",
        "\n",
        "# Extract sequence exampls\n",
        "for record in dataset:\n",
        "  sequence_example = tf.train.SequenceExample()\n",
        "  sequence_example.ParseFromString(record.numpy())\n",
        "\n",
        "  label_id = -1\n",
        "  max_label_id = 0\n",
        "\n",
        "  # Find label id, accel dimentionality, and accel window size.\n",
        "  dims = 0\n",
        "  window_size = -1\n",
        "  for feature_name, feature in sequence_example.context.feature.items():\n",
        "    if feature_name == CLASS_FEATURE_KEY_ID:\n",
        "      label_id = feature.int64_list.value[0]\n",
        "    if feature_name == DIM_FEATURE_NAME:\n",
        "      dims = feature.int64_list.value[0]\n",
        "    if feature_name == WINDOW_SIZE_FEATURE_NAME and window_size \u003c 1:\n",
        "      window_size = feature.int64_list.value[0]\n",
        "\n",
        "  if dims == 0:\n",
        "    print('WARNING: Got sequence example without dimensions for'\n",
        "          'ACCELEROMETER_WINDOW')\n",
        "    continue\n",
        "\n",
        "  if label_id \u003c 0:\n",
        "    print('WARNING: Label ID less than 0')\n",
        "    continue\n",
        "\n",
        "  if label_id \u003e max_label_id:\n",
        "    max_label_id = label_id\n",
        "\n",
        "  for (feature_name,\n",
        "       feature_list) in sequence_example.feature_lists.feature_list.items():\n",
        "    if feature_name != DATA_FEATURE_NAME:\n",
        "      continue\n",
        "\n",
        "    num_features = len(feature_list.feature)\n",
        "    if window_size \u003e 0 and num_features % window_size != 0:\n",
        "      print('WARNING: Window size misaligned with number of features')\n",
        "      continue\n",
        "\n",
        "    if window_size \u003c 0:\n",
        "      # Each element in the dataset is a sensor datapoint.\n",
        "      full_trace = []\n",
        "      for feature in feature_list.feature:\n",
        "        if len(feature.float_list.value) != dims:\n",
        "          print('WARNING: Got data with incorrect dimensions')\n",
        "          continue\n",
        "        full_trace.extend(feature.float_list.value)\n",
        "      labeled_dataset[label_id].append(full_trace)\n",
        "    else:\n",
        "      # Each element in the dataset is a window.\n",
        "      num_windows = int(num_features / window_size)\n",
        "      for window_idx in range(num_windows):\n",
        "        windowed_data = [None] * (window_size * dims)\n",
        "        for data_idx in range(window_size):\n",
        "          for data_dim_idx in range(dims):\n",
        "            windowed_data[(data_idx * dims) +\n",
        "                          data_dim_idx] = feature_list.feature[\n",
        "                              (window_idx * window_size) +\n",
        "                              data_idx].float_list.value[data_dim_idx]\n",
        "        labeled_dataset[label_id].append(windowed_data)\n",
        "\n",
        "for label_id, items in labeled_dataset.items():\n",
        "  labeled_dataset[label_id] = np.array(items)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tQs_mOJNxxqv"
      },
      "outputs": [],
      "source": [
        "# Split data between training, validation, and testing\n",
        "label_ids = labeled_dataset.keys()\n",
        "dataset_split_names = {'train', 'validation', 'test'}\n",
        "np_split_dataset = {'train': {}, 'validation': {}, 'test': {}}\n",
        "for label_id in label_ids:\n",
        "  np_split_dataset['test'][label_id], temp = train_test_split(\n",
        "      labeled_dataset[label_id], test_size=PERCENT_TEST)\n",
        "  np_split_dataset['train'][label_id], np_split_dataset['validation'][\n",
        "      label_id] = train_test_split(\n",
        "          temp, test_size=PERCENT_TRAIN / (PERCENT_TRAIN + PERCENT_VALIDATION))\n",
        "\n",
        "# Add labels and shuffle the data.\n",
        "tf_split_datasets = {}\n",
        "for split_name in dataset_split_names:\n",
        "  examples = []\n",
        "  labels = []\n",
        "  for label_id in label_ids:\n",
        "    examples.extend(np_split_dataset[split_name][label_id])\n",
        "    labels.extend(\n",
        "        np.full(len(np_split_dataset[split_name][label_id]), label_id))\n",
        "  tf_split_datasets[split_name] = tf.data.Dataset.from_tensor_slices(\n",
        "      (np.array(examples),\n",
        "       np.array(labels))).shuffle(len(examples)).batch(DATASET_BATCH_SIZE)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "16m1ndo6S5Xt"
      },
      "outputs": [],
      "source": [
        "# Binary training\n",
        "assert len(label_ids) == 2\n",
        "\n",
        "# Create model\n",
        "binary_model = keras.Sequential([\n",
        "    keras.layers.Flatten(input_shape=labeled_dataset[0][0].shape),\n",
        "    keras.layers.Dense(40, activation='relu'),\n",
        "    keras.layers.Dropout(0.3),\n",
        "    keras.layers.Dense(20, activation='relu'),\n",
        "    keras.layers.Dense(1, activation='sigmoid')\n",
        "])\n",
        "binary_model.compile(\n",
        "    optimizer='adam',\n",
        "    loss=tf.keras.losses.BinaryCrossentropy(),\n",
        "    metrics=[\n",
        "        tf.keras.metrics.BinaryAccuracy(),\n",
        "        tf.keras.metrics.TruePositives(),\n",
        "        tf.keras.metrics.FalsePositives(),\n",
        "        tf.keras.metrics.TrueNegatives(),\n",
        "        tf.keras.metrics.FalseNegatives()\n",
        "    ])\n",
        "\n",
        "# Train model.\n",
        "binary_model.fit(\n",
        "    x=tf_split_datasets['train'],\n",
        "    epochs=15,\n",
        "    validation_data=tf_split_datasets['validation'])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YR9bR_qr40ae"
      },
      "outputs": [],
      "source": [
        "# Test model\n",
        "test_loss, test_acc, true_pos, false_pos, true_neg, false_neg = binary_model.evaluate(\n",
        "    tf_split_datasets['test'], verbose=1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lDgMFttPe-zz"
      },
      "outputs": [],
      "source": [
        "# Save model\n",
        "binary_model.save(SAVED_MODEL_FOLDER)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GNezjUcX4i8W"
      },
      "outputs": [],
      "source": [
        "# Multiclass training\n",
        "\n",
        "# Create model\n",
        "multiclass_model = keras.Sequential([\n",
        "    keras.layers.Flatten(input_shape=labeled_dataset[0][0].shape),\n",
        "    keras.layers.Dense(40, activation='relu'),\n",
        "    keras.layers.Dropout(0.3),\n",
        "    keras.layers.Dense(len(label_ids), activation='softmax'),\n",
        "])\n",
        "multiclass_model.compile(\n",
        "    optimizer='adam',\n",
        "    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),\n",
        "    metrics=['accuracy'])\n",
        "\n",
        "# Train model.\n",
        "multiclass_model.fit(\n",
        "    x=tf_split_datasets['train'],\n",
        "    epochs=15,\n",
        "    validation_data=tf_split_datasets['validation'])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VDzn3EL-9DXD"
      },
      "outputs": [],
      "source": [
        "# Test model\n",
        "test_loss, test_acc = multiclass_model.evaluate(tf_split_datasets['test'], verbose=1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BDMcxg-htz9T"
      },
      "outputs": [],
      "source": [
        "# Save model\n",
        "multiclass_model.save(SAVED_MODEL_FOLDER)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "02htaRlBtzpj"
      },
      "source": [
        ""
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "last_runtime": {
        "build_target": "",
        "kind": "local"
      },
      "name": "intent_recognition_training.ipynb",
      "private_outputs": true,
      "provenance": [
        {
          "file_id": "1MBeUV0Gn9SRnJPMZgepWm58PO-p8KS3F",
          "timestamp": 1658993689342
        },
        {
          "file_id": "1M2N96MktxpOXc_eRb5Rxsci8Y4d8WfuV",
          "timestamp": 1653793187682
        }
      ]
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
